package com.ihr360.authority.sharing.util;

import com.ihr360.authority.sharing.model.IResourceControl;
import com.ihr360.authority.sharing.model.ResourceAccess;
import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.commons.model.type.AccessPrivilege;
import com.ihr360.commons.model.type.ResourcePublicity;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.Map;

public abstract  class AccessControlUtils {
    private  final static String ID="id";

    public static void setAccessControl2Target(Object target, Map<Long, Integer> privilegeMap, Map<Long, Integer> publicityMap) {
        IResourceControl control = (IResourceControl)target;
        ResourceAccess resourceAccess=control.getResourceAccess();
        if (resourceAccess==null){
            resourceAccess = new ResourceAccess();
            control.setResourceAccess(resourceAccess);
        }
        BeanWrapper beanWrapper = new BeanWrapperImpl(target);
        Object objId = beanWrapper.getPropertyValue(ID);

        if (CollectionUtils.isNotEmpty(privilegeMap)) {
            Integer privilege = privilegeMap.get(objId);
            resourceAccess.setAccessPrivilege(AccessPrivilege.getAccessPrivilege(privilege));
        }

        if (CollectionUtils.isNotEmpty(publicityMap)) {
            Integer publicity = publicityMap.get(objId);
            resourceAccess.setResourcePublicity(ResourcePublicity.getResourcePublicity(publicity));
        }
        control.setResourceAccess(resourceAccess);
    }

    public static void setAccessControl2Target(Object target, Integer privilege, Integer publicity) {
        IResourceControl control = (IResourceControl)target;
        ResourceAccess resourceAccess=control.getResourceAccess();
        if (resourceAccess==null){
            resourceAccess = new ResourceAccess();
            control.setResourceAccess(resourceAccess);
        }
        resourceAccess.setAccessPrivilege(AccessPrivilege.getAccessPrivilege(privilege));
        resourceAccess.setResourcePublicity(ResourcePublicity.getResourcePublicity(publicity));
        control.setResourceAccess(resourceAccess);
    }
}